import React from 'react';
import {
  Row,
  Col,
  Select,
  Button,
  Input,
  Form,
  Spin,
  Table,
  Pagination,
  message,
  Modal
} from 'antd';
const { confirm } = Modal;
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  CloseOutlined,
} from '@ant-design/icons';
// import { Page } from 'components'
import styles from './index.less';
import { connect } from 'dva';

import AddModal from './addDictKeyModal';

@Form.create()
@connect(({ system }) => ({ ...system }))
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currDictName: '',
      timestamp: '',
      checkColumns: [
        { title: '字典值名称', dataIndex: 'name', key: 'name' },
        { title: '字典值编码', dataIndex: 'dictValueId', key: 'dictValueId'},
        { title: '详情', dataIndex: 'remark', key: 'remark' },
        { title: '创建时间', dataIndex: 'createdDt', key: 'createdDt' },
        {
          title: '操作',
          dataIndex: 'cz',
          width: 200,
          render: (text, record) => (
            <p className={styles.tableBtns}>
              <a onClick={() => this.updateData(record)}>
                <EditOutlined />
                修改
              </a>
              <a onClick={() => this.deleteData(record)}>
                <CloseOutlined />
                删除
              </a>
            </p>
          ),
        },
      ],
      dataList: [],
      totalPage: 1,
      pageSize: 10,
      totalData: 3,
      currentPage: 1,
      loading: false,
      addModalVisible: false,
      addTimestamp: Date.parse(new Date()),
      addLoading: false,
      dictDetail: {}, //当前用户详情
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.querySever();
  };

  //获取用户列表
  querySever = async () => {
    this.setState({ loading: true });
    const { props } = this;
    await props
      .dispatch({
        type: 'system/queryDictKeyList',
        payload: {
            // dir: "asc",
            dictId: location.pathname.match('[^/]+(?!.*/)')[0],
            name: this.state.currDictName,
            page: this.state.currentPage,
            rows: this.state.pageSize
        },
      })
      .then(res => {
        this.setState({
          loading: false,
          dataList: res.list ? res.list : [],
          totalData: res.total,
        });
        console.log(res, 'res');
      });
  };

  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  //用户名称修改
  dictNameChange = e => {
    this.setState({
      currDictName: e.target.value,
    });
  };

  //提交订单
  submitFun = () => {
    this.init();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currDictName: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.init();
      },
    );
  };

  //修改信息
  updateData = record => {
    // this.queryPwdChangeServer();
    this.setState({
      dictDetail: record,
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  //删除信息
  deleteData = record => {
    const _this = this;
    confirm({
      // icon: <ExclamationCircleOutlined />,
      content: `确认删除【${record.name}】?`,
      onOk() {
        console.log('OK');
        const { dispatch } = _this.props;
        dispatch({
          type: 'system/deleteKeyDictPost',
          payload: {
            dictValueId: record.dictValueId
          },
        }).then(res => {
          if(res.success){
            if (res.code == 0) {
              message.success('删除成功！');
            } else {
              message.error(res.msg);
            }
            _this.init()
          }else {
            message.error(res.msg);
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.init();
      },
    );
  };

  get addModalProps() {
    const { addModalVisible, dictDetail, addLoading } = this.state;
    let _this = this;
    return {
      title: '字典值管理',
      visible: addModalVisible,
      dictDetail: dictDetail,
      loading: addLoading,
      width: '700px',
      okText: '提交',
      cancelText: '取消',
      onOk: data => {
        _this.setState(
          {
            loading: true,
          },
          () => {
            data.dictId = location.pathname.match('[^/]+(?!.*/)')[0];
            const { dispatch } = _this.props;
            dispatch({
              type: data.dictValueId==''?'system/addKeyDictPost':'system/editKeyDictPost',
              payload: data,
            }).then(res => {
              if(res.success){
                if (res.code == 0) {
                  message.success(data.dictValueId==''?'新增成功！':'修改成功！');
                } else {
                  message.error(res.msg);
                }
                _this.setState(
                  {
                    loading: false,
                    addModalVisible: false,
                  },
                  () => {
                    _this.init();
                  },
                );
              }else {
                message.error(res.msg);
              }
            });
          },
        );
      },
      onCancel() {
        _this.setState({
          addModalVisible: false,
        });
      },
    };
  }

  //新增用户
  addFun = () => {
    // this.queryPwdChangeServer();
    this.setState({
      dictDetail: {
        dictId: '',
        name: '',
        dickKey: '',
        remark: '',
        // ...this.state.dictDetail,
      },
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  render() {
    const { checkColumns, orgList, dataList, addTimestamp, roleTimestamp, timestamp } = this.state;

    const { getFieldDecorator } = this.props.form;
    return (
      <div className={styles.mainPage}>
        <Row>
          <Col span={24}>
            <dl key={timestamp+1}>
              <dt>
                <Form name="horizontal_search" layout="inline">
                  <Form.Item name="username" label="">
                    <Input
                      style={{ width: 300 }}
                      type="text"
                      placeholder="请输入名称搜索"
                      defaultValue={this.state.currDictName}
                      onChange={this.dictNameChange}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" onClick={this.submitFun}>
                      <SearchOutlined />
                      搜索
                    </Button>
                    <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                      <SyncOutlined />
                      重置
                    </Button>
                  </Form.Item>
                  <Form.Item style={{ float: 'right' }}>
                    <Button type="primary" onClick={this.addFun}>
                      <PlusOutlined />
                      新增
                    </Button>
                  </Form.Item>
                </Form>
              </dt>
              <dd>
                <AddModal key={addTimestamp} {...this.addModalProps} />
                {/* <RoleModal key={roleTimestamp} {...this.roleModalProps} /> */}
                <Spin spinning={this.state.loading} delay={500}>
                  <Table
                    style={{ marginTop: '20px' }}
                    bordered
                    columns={checkColumns}
                    dataSource={dataList}
                    simple
                    // scroll={{ x: 1200 }}
                    pagination={false}
                    // rowSelection={rowSelection}
                  />
                </Spin>
                <p style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Pagination
                    current={this.state.currentPage}
                    pageSize={this.state.pageSize}
                    total={this.state.totalData}
                    onChange={this.pageChange}
                  />
                </p>
              </dd>
            </dl>
          </Col>
        </Row>
      </div>
    );
  }
}

export default Index;
